package com.ruoyi.web.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.web.article.domain.TrainArticle;
import com.ruoyi.web.article.domain.TrainArticleReadRecord;
import com.ruoyi.web.article.mapper.TrainArticleMapper;
import com.ruoyi.web.article.mapper.TrainArticleReadRecordMapper;
import com.ruoyi.web.article.service.ITrainArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * 文章Service业务层处理
 *
 * @author 范书铭
 * @date 2024-10-13
 */
@Service
public class TrainArticleServiceImpl extends ServiceImpl<TrainArticleMapper, TrainArticle> implements ITrainArticleService {
    @Autowired
    private TrainArticleMapper trainArticleMapper;
    @Autowired
    TrainArticleReadRecordMapper trainArticleReadRecordMapper;
    @Autowired
    SysUserMapper sysUserMapper;

    /**
     * 查询文章列表
     *
     * @param trainArticle 文章
     * @return 文章
     */
    @Override
    public List<TrainArticle> selectTrainArticleList(TrainArticle trainArticle) {
        return trainArticleMapper.selectTrainArticleList(trainArticle);
    }

    @Transactional
    @Override
    public TrainArticle getArticleById(Long id, Long userId) {
        TrainArticle trainArticle = trainArticleMapper.selectById(id);
        //添加阅读记录
        trainArticle.setReadTimes(trainArticle.getReadTimes() + 1L);
        save(trainArticle);
        TrainArticleReadRecord trainArticleReadRecord = new TrainArticleReadRecord();
        trainArticleReadRecord.setArticleId(id);
        trainArticleReadRecord.setUserId(userId);
        trainArticleReadRecordMapper.insert(trainArticleReadRecord);
        return trainArticle;
    }

    @Override
    public List<TrainArticle> selectUserHistory(Long userId) {
        return trainArticleMapper.selectUserHistory(userId);
    }

    @Override
    public List<SysUser> selectArticleHistory(Long articleId) {
        List<Long> userIds = trainArticleReadRecordMapper.selectList(new LambdaQueryWrapper<TrainArticleReadRecord>()
                        .eq(TrainArticleReadRecord::getArticleId, articleId))
                .stream().map(TrainArticleReadRecord::getUserId).collect(Collectors.toList());
        return sysUserMapper.selectBatchIds(userIds).stream()
                .peek(sysUser -> sysUser.setPassword(null))
                .collect(Collectors.toList());
    }

    @Override
    public List<TrainArticle> userCollectionArticle(Long userId) {
        return null;
    }
}